<template>
  <div class="employee-container">

    <div class="search-container">
      <span class="search-label">员工姓名: </span>
      <el-input v-model="params.name" class="search-main" placeholder="请输入员工姓名"></el-input>
      <el-button class="search-btn" type="primary" @click="searchEmployee">搜索</el-button>
    </div>

    <div class="create-container">
      <el-button type="primary" @click="handleCreate">新增员工</el-button>
    </div>

    <div class="table">
      <el-table :data="employeeList" style="width: 100%;">
        <el-table-column type="index" width="55"></el-table-column>
        <el-table-column label="员工姓名" prop="name"></el-table-column>
        <el-table-column label="员工账号" prop="userName"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="员工电话" prop="phonenumber"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="createTime"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" size="mini" @click="resetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        layout="total,  prev, pager, next"
        :current-page.sync="params.page"
        :page-size.sync="params.pageSize"
        :total="total"
        @current-change="onChangeEmployee"
      >
      </el-pagination>
    </div>

    <!--    -->
    <el-dialog
      title="添加员工"
      :visible.sync="dialogVisible"
      width="45%"
      @close="closeDialog"
      @open="openDialog"
    >
      <div class="form-container">
        <el-form ref="employeeForm" :model="employeeForm" :rules="employeeRuleForm" label-width="100px">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="employeeForm.name"></el-input>
          </el-form-item>
          <el-form-item label="员工账号" prop="userName">
            <el-input v-model="employeeForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="phonenumber">
            <el-input v-model="employeeForm.phonenumber"></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleId">
            <el-select v-model="employeeForm.roleId">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="employeeForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleCancel">取消</el-button>
        <el-button type="default" @click="handleAdd">确定</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script>
import { getUserListAPI, createUserAPI, updateUserAPI, delUserAPI } from '@/api/user'
import { getRoleListAPI } from '@/api/role'

export default {
  name: 'Employee',
  data() {
    return {
      params: {
        page: 1,
        pageSize: 2,
        name: ''
      },
      employeeList: [],
      total: 0,
      employeeForm: {
        name: '',
        userName: '',
        phonenumber: '',
        roleName: '',
        roleId: '',
        status: ''
      },
      employeeRuleForm: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入员工账号', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]

      },
      dialogVisible: false,
      roleList: [],
      userId: ''

    }
  },
  mounted() {
    this.searchEmployee()
  },
  methods: {
    async getRoleList() {
      // 调用接口获取角色列表
      const res = await getRoleListAPI(this.params)
      if (res.code === 10000) {
        this.roleList = res.data
      }
    },
    async searchEmployee() {
      // console.log(this.searchName)
      const res = await getUserListAPI(this.params)
      if (res.code === 10000) {
        this.employeeList = res.data.rows
        this.total = res.data.total
      }
    },
    handleCreate() {
      this.dialogVisible = true
      this.employeeForm = {
        name: '',
        userName: '',
        phonenumber: '',
        roleName: '',
        roleId: '',
        status: ''
      }
      this.getRoleList()
    },
    handleEdit(row) {
      // console.log('============== edit==================', row)
      this.getRoleList()
      this.employeeForm = row // 赋值给表单
      this.dialogVisible = true
      this.userId = row.id
    },
    handleDelete(row) {
      const user_id = row.id
      // console.log('============== delete==================', row)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 调用接口删除员工
        console.log('============== delete==================', user_id)
        const res = await delUserAPI(user_id)
        if (res.code === 10000) {
          this.searchEmployee()
          this.$message.success('删除员工成功')
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.$message.error('已取消删除')
      })
    },
    onChangeEmployee(page) {
      this.params.page = page
      this.searchEmployee()
    },
    resetPassword(row) {
      this.$message.success('重置密码成功')
      this.searchEmployee()
    },
    handleAdd() {
      this.$refs.employeeForm.validate(async valid => {
        if (valid) {
          // 修改
          if (this.userId) {
            // 调用接口修改员工
            delete this.employeeForm.createTime
            console.log('============== 修改员工==================', this.employeeForm)
            const res = await updateUserAPI(this.employeeForm)
            if (res.code === 10000) {
              this.dialogVisible = false
              this.searchEmployee()
              this.$message.success('修改员工成功')
            } else {
              this.$message.error(res.msg)
              return false
            }
          } else {
            // 填充 roleName
            this.roleList.filter(item => {
              if (item.roleId === this.employeeForm.roleId) {
                this.employeeForm.roleName = item.roleName
              }
            })
            // this.employeeForm['password'] = '12345678' 非必须传递字段
            console.log(' =============== 提交的表单数据内容是 ===================', this.employeeForm)
            // 调用接口添加员工
            const res = await createUserAPI(this.employeeForm)
            if (res.code === 10000) {
              this.dialogVisible = false
              this.searchEmployee()
              this.$message.success('添加员工成功')
            } else {
              this.$message.error(res.msg)
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.dialogVisible = false
      this.employeeForm = {
        name: '', userName: '', phonenumber: '', roleName: '', roleId: '', status: ''
      }
    },
    closeDialog() {
      this.dialogVisible = false
    },
    openDialog() {
      this.dialogVisible = true
    },
    // 适配员工状态
    formatStatus(status) {
      return status === 1 ? '启用' : '禁用'
    }
  }
}
</script>

<style lang="scss" scoped>
.employee-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
    margin-left: 15px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 10px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}


</style>
